#pysocial/utils.py
#collection of helper functions
import urllib
import urllib2
import socket
import types
import base64
import simplejson

def list_from_comma_string(list_of_strings):
    """ Return list of strings separated by commas"""
    return [i.strip() for i in list_of_strings.split(',') if i.strip()]

def friendlyURLEncode(data):
    # makes sure that for every item in your data dictionary that is of unicode type, it is first UTF-8
    # encoded before passing it in to urllib.urlencode()
    data = dict([(k, v.encode('utf-8') if type(v) is types.UnicodeType else v) for (k, v) in data.items()])
    return urllib.urlencode(data)

def to_uri(iri):
    if iri is None:
        return iri

    #handle unicode
    temp = iri
    if isinstance(temp, unicode):
        iri = temp.encode('utf-8', 'strict')
    elif not isinstance(temp, basestring):
        try:
            iri =  str(temp)
        except UnicodeEncodeError:
            iri = unicode(temp).encode('utf-8', 'strict')
    else:
        iri = temp

    return urllib.quote(iri, safe="/#%[]=:;$&()+,!?*@'~")

def makeAPICall(domain, apiHandler, postData=None, rawPostData=None, queryData=None, userName=None,
                 password=None, secure=True, timeout=5, deserializeAs='json', headers={}):
    """
    This is copy/pasta from
    https://github.com/joelsemar/django-webservice-tools/webservice_tools/utils.py
    """
    assert deserializeAs in ('xml', 'json', 'utf-8', 'skip', None)
    requestType = secure and "https" or "http"

    url = "%s://%s/%s" % (requestType, domain, to_uri(apiHandler))

    if queryData:
        queryString = urllib.urlencode(queryData)
        url += "?" + queryString

    req = urllib2.Request(url)

    if headers:
        for k, v in headers.items():
            req.add_header(k, v)

    if userName is not None and password is not None:
        base64String = base64.encodestring('%s:%s' % (userName, password)).rstrip('\n')
        authheader = 'Basic %s' % base64String
        req.add_header('Authorization', authheader)

    defaultTimeout = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(timeout)
        if postData:
            params = friendlyURLEncode(postData)
            response = urllib2.urlopen(req, params)

        elif rawPostData:
            response = urllib2.urlopen(req, rawPostData)

        else:
            response = urllib2.urlopen(req)

        if deserializeAs == 'json':
            response = simplejson.load(response, encoding='utf-8')

        elif deserializeAs == 'utf-8': #skip
            response = response.read().decode('utf-8')

        elif deserializeAs == None: # don't decode
            response = response.read()

        elif deserializeAs == "skip":
            pass

    finally:
        socket.setdefaulttimeout(defaultTimeout)

    return response
